﻿Option Explicit On

Public Class frmFerramentasCaracteres
    Private strPKChave As String = ""

    Private Sub frmFerramentasReplacer_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Call MontaGrid()
        Call CancelarOperacao()
    End Sub

    Private Sub MontaGrid()
        Try
            With dgvResult
                .SelectionMode = DataGridViewSelectionMode.FullRowSelect
                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False
                .AllowUserToResizeRows = False
                '.AlternatingRowsDefaultCellStyle.BackColor = Color.DarkGray'-- zebrado
                .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
                .MultiSelect = False
                .ConnectionString = strMyDBString
                .TypeConnection = AnguloGridView.EnumTypeConection.SQLiteDataAdapter
                .SQL = "SELECT char_orig, char_dest " & _
                       "FROM replacer " & _
                       "ORDER BY char_orig ASC"
                .AddColumn("Carac.", 0, , DataGridViewContentAlignment.MiddleLeft)
                .AddColumn("Substituto", 150, , DataGridViewContentAlignment.MiddleLeft)
            End With
        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        End Try
    End Sub

    Private Sub tbPadrao_ItemClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles tbPadrao.ItemClicked
        Try
            Select Case e.ClickedItem.Tag
                Case "IN"
                    Call Novoregistro()
                Case "ED", "AL"
                    Call EditarDados()
                Case "GR"
                    Call GravarRegistro()
                Case "CR", "CA"
                    Call CancelarOperacao()
                Case "EX"
                    Call ApagarDados()
            End Select
        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        End Try
    End Sub

    Private Sub Novoregistro()
        tbPadrao.ToolOrder("IN")
        gpbItem.Enabled = True
        txtCharOrig.Select()
    End Sub

    Private Sub EditarDados()
        Try
            strPKChave = TrataNull(dgvResult.CurrentRow.Cells(0).Value, TypeCode.String)
            If Not IsEmpty(strPKChave) Then
                Call PuxarDados()
            End If
        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        End Try
    End Sub

    Private Sub PuxarDados()
        Try
            mySQLite.Query("SELECT char_orig, char_dest " & _
                                   "FROM replacer " & _
                                   "WHERE char_orig='" & strPKChave & "'")
            If Not mySQLite.EOF Then
                txtCharOrig.Text = TrataNull(mySQLite.Field("char_orig"), TypeCode.String)
                txtCharDest.Text = TrataNull(mySQLite.Field("char_dest"), TypeCode.String)
                '--
                tbPadrao.ToolOrder("ED")
                gpbItem.Enabled = True
                txtCharOrig.Enabled = False
                txtCharDest.Select()
            End If
        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        End Try
    End Sub

    Private Sub GravarRegistro()
        If IsEmpty(txtCharOrig.Text) Then
            Call MsgBox("Preencha o caractere a ser trocado!", MsgBoxStyle.Exclamation)
            txtCharOrig.Select()
            Exit Sub
        End If
        Call GravarDados()
        Call CancelarOperacao()
    End Sub

    Private Sub GravarDados()
        Try
            mySQLite.Query("SELECT * FROM replacer WHERE char_orig='" & TrataNull(txtCharOrig.Text, TypeCode.String) & "'")
            If mySQLite.EOF Then
                mySQLite.Execute("INSERT INTO replacer(char_orig, char_dest) VALUES('" & TrataNull(txtCharOrig.Text, TypeCode.String) & "','" & TrataNull(txtCharDest.Text, TypeCode.String) & "')")
            Else
                mySQLite.Execute("UPDATE replacer " & _
                                 "SET char_dest='" & ConvToHTML(txtCharDest.Text) & "' " & _
                                 "WHERE char_orig='" & TrataNull(txtCharOrig.Text, TypeCode.String) & "'")
            End If
        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        End Try
    End Sub

    Private Function ConvToHTML(ByVal strEntrada As String) As String
        Dim strOut As String = ""
        Dim strChar, strToParse As String
        For intCount As Integer = 1 To strEntrada.Length
            strChar = Mid(strEntrada, intCount, 1)
            If strChar Like "[a-zA-Z0-9 ]" Then
                strOut &= strChar
            Else
                strToParse = strChar
                For intChar As Integer = 0 To dgvResult.RowCount - 1
                    If dgvResult.TextMatrix(intChar, 0) = strChar Then
                        strToParse = dgvResult.TextMatrix(intChar, 1)
                        Exit For
                    End If
                Next
                strOut &= strToParse
            End If
        Next
        Return strOut
    End Function

    Private Sub CancelarOperacao()
        Call LimpaForm(gpbItem)
        tbPadrao.ToolOrder("CA")
        gpbItem.Enabled = False
        txtCharOrig.Enabled = True
        strPKChave = ""
        dgvResult.Reload()
    End Sub

    Private Sub ApagarDados()
        Try
            If MsgBox("Apagar este lançamento?", MsgBoxStyle.Question + MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
                mySQLite.Execute("DELETE FROM replacer WHERE char_orig='" & strPKChave & "'")
            End If
            Call CancelarOperacao()
        Catch ex As Exception
            Select Case Err.Number
                Case -2147467259
                    Call MsgBox("Este registro não pode ser excluído, pois está lançando em outra tela!", MsgBoxStyle.Exclamation)
                Case Else
                    Call MsgBox(Err.Description, MsgBoxStyle.Exclamation)
            End Select
            Call SendError(ex.Message, ex.StackTrace)
        End Try
    End Sub

    Private Sub txtCharOrig_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtCharOrig.Validating
        With dgvResult
            For intRow As Integer = 0 To .RowCount - 1
                If .TextMatrix(intRow, 0) = txtCharOrig.Text.Trim Then
                    Call MsgBox("Este caractere já está cadastrado!", MsgBoxStyle.Exclamation)
                    e.Cancel = True
                    Exit For
                End If
            Next
        End With
    End Sub
End Class